import { problem } from '@/api/protobuf-loader';
import { userStats } from './user';

// 题目数据缓存
const problemCache = new Map()

// 题目数据数组
const problemData = [
  {
    id: 1,
    title: '两数之和',
    description: '给定一个整数数组 nums 和一个目标值 target，请你在该数组中找出和为目标值的那两个整数，并返回他们的数组下标。',
    difficulty: 1, // uint32类型表示难度等级(1=简单,2=中等,3=困难)
    tags: ['数组', '哈希表'],
    template: {
      cpp : `
      #include <iostream>
      
      int main() {
          std::cout << "Hello, C++ in Monaco!" << std::endl;
          return 0;
      }`,
    java:`
      public class Main {
          public static void main(String[] args) {
              System.out.println("Hello, Java in Monaco!");
          }
      }`,
      python:`
      def main():
          print("Hello, Python in Monaco!")
      
      if __name__ == "__main__":
          main()`
    },
    acceptanceRate: 72.5,
    testCases: [
      {
        input: 'nums = [2,7,11,15], target = 9',
        output: '[0,1]',
        explanation: '数组第0位2和第1位7相加等于9'
      },
      {
        input: 'nums = [3,2,4], target = 6',
        output: '[1,2]',
        explanation: '数组第1位2和第2位4相加等于6'
      }
    ],
    testCaseHint: [
      "2 <= nums.length <= 104",
      "-109 <= nums[i] <= 109"
    ]
  },
  {
    id: 2, 
    title: '反转链表',
    description: '反转一个单链表。',
    difficulty: 1,
    tags: ['链表'],
    template: {
            cpp : `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`,
          java:`
            public class Main {
                public static void main(String[] args) {
                    System.out.println("Hello, Java in Monaco!");
                }
            }`,
            python:`
            def main():
                print("Hello, Python in Monaco!")
            
            if __name__ == "__main__":
                main()`
          },
    acceptanceRate: 62.3,
    testCases: [
      {
        input: '1->2->3->4->5->NULL',
        output: '5->4->3->2->1->NULL',
        explanation: '链表反转后的结果'
      },
      {
        input: '1->NULL',
        output: '1->NULL',
        explanation: '单节点链表反转后不变'
      }
    ],
    testCaseHint: [
      "2 <= nums.length <= 104",
      "-109 <= nums[i] <= 109"
    ]
  },
  {
    id: 3,
    title: '无重复字符的最长子串',
    description: '给定一个字符串，请你找出其中不含有重复字符的最长子串的长度。',
    difficulty: 2,
    tags: ['哈希表', '双指针', '字符串'],
    template: {
            cpp : `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`,
          
          java:`
            public class Main {
                public static void main(String[] args) {
                    System.out.println("Hello, Java in Monaco!");
                }
            }`,
            python:`
            def main():
                print("Hello, Python in Monaco!")
            
            if __name__ == "__main__":
                main()`
          },
          testCaseHint: [
            "2 <= nums.length <= 104",
            "-109 <= nums[i] <= 109"
          ]
  },
  {
    id: 4,
    title: '寻找两个正序数组的中位数',
    description: '给定两个大小分别为 m 和 n 的正序（从小到大）数组 nums1 和 nums2。请你找出并返回这两个正序数组的中位数。',
    difficulty: 3,
    tags: ['数组', '二分查找'],
    template:{
            cpp : `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`,
          java:`
            public class Main {
                public static void main(String[] args) {
                    System.out.println("Hello, Java in Monaco!");
                }
            }`,
            python:`
            def main():
                print("Hello, Python in Monaco!")
            
            if __name__ == "__main__":
                main()`
          },
          testCaseHint: [
            "2 <= nums.length <= 104",
            "-109 <= nums[i] <= 109"
          ]
  },
  {
    id: 5,
    title: '最长回文子串',
    description: '给你一个字符串 s，找到 s 中最长的回文子串。',
    difficulty: 2,
    tags: ['字符串', '动态规划'],
    template: {
            cpp : `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`,
          java:`
            public class Main {
                public static void main(String[] args) {
                    System.out.println("Hello, Java in Monaco!");
                }
            }`,
            python:`
            def main():
                print("Hello, Python in Monaco!")
            
            if __name__ == "__main__":
                main()`
          },
          testCaseHint: [
            "2 <= nums.length <= 104",
            "-109 <= nums[i] <= 109"
          ]
  },
  {
    id: 6,
    title: 'Z字形变换',
    description: '将一个给定字符串 s 根据给定的行数 numRows ，以从上往下、从左到右进行 Z 字形排列。',
    difficulty: 2,
    tags: ['字符串'],
    template:{
            cpp : `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`,
          java:`
            public class Main {
                public static void main(String[] args) {
                    System.out.println("Hello, Java in Monaco!");
                }
            }`,
            python:`
            def main():
                print("Hello, Python in Monaco!")
            
            if __name__ == "__main__":
                main()`
          },
          testCaseHint: [
            "2 <= nums.length <= 104",
            "-109 <= nums[i] <= 109"
          ]
  },
  {
    id: 7,
    title: '整数反转',
    description: '给你一个 32 位的有符号整数 x ，返回将 x 中的数字部分反转后的结果。',
    difficulty: 1,
    tags: ['数学'],
    template:{
            cpp : `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`,
          java:`
            public class Main {
                public static void main(String[] args) {
                    System.out.println("Hello, Java in Monaco!");
                }
            }`,
            python:`
            def main():
                print("Hello, Python in Monaco!")
            
            if __name__ == "__main__":
                main()`
          },
          testCaseHint: [
            "2 <= nums.length <= 104",
            "-109 <= nums[i] <= 109"
          ]
  },
  {
    id: 8,
    title: '字符串转换整数',
    description: '请你来实现一个 myAtoi(string s) 函数，使其能将字符串转换成一个 32 位有符号整数。',
    difficulty: 2,
    tags: ['字符串'],
    template: {
            cpp : `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`,
          java:`
            public class Main {
                public static void main(String[] args) {
                    System.out.println("Hello, Java in Monaco!");
                }
            }`,
            python:`
            def main():
                print("Hello, Python in Monaco!")
            
            if __name__ == "__main__":
                main()`
          },
          testCaseHint: [
            "2 <= nums.length <= 104",
            "-109 <= nums[i] <= 109"
          ]
  },
  {
    id: 9,
    title: '回文数',
    description: '给你一个整数 x ，如果 x 是一个回文整数，返回 true ；否则，返回 false 。',
    difficulty: 1,
    tags: ['数学'],
    template:{
            cpp : `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`,
          java:`
            public class Main {
                public static void main(String[] args) {
                    System.out.println("Hello, Java in Monaco!");
                }
            }`,
            python:`
            def main():
                print("Hello, Python in Monaco!")
            
            if __name__ == "__main__":
                main()`
          },
          testCaseHint: [
            "2 <= nums.length <= 104",
            "-109 <= nums[i] <= 109"
          ]
  },
  {
    id: 10,
    title: '正则表达式匹配',
    description: '给你一个字符串 s 和一个字符规律 p，请你来实现一个支持 \'.\' 和 \'*\' 的正则表达式匹配。',
    difficulty: 3,
    tags: ['字符串', '动态规划'],
    template:{
            cpp : `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`,
          java:`
            public class Main {
                public static void main(String[] args) {
                    System.out.println("Hello, Java in Monaco!");
                }
            }`,
            python:`
            def main():
                print("Hello, Python in Monaco!")
            
            if __name__ == "__main__":
                main()`
          },
          testCaseHint: [
            "2 <= nums.length <= 104",
            "-109 <= nums[i] <= 109"
          ]
  },
  {
    id: 11,
    title: '盛最多水的容器',
    description: '给你 n 个非负整数 a1，a2，...，an，每个数代表坐标中的一个点 (i, ai)。在坐标内画 n 条垂直线，使得线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线，使得它们与 x 轴共同构成的容器可以容纳最多的水。',
    difficulty: 2,
    tags: ['数组', '双指针'],
    template:{
            cpp : `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`,
          java:`
            public class Main {
                public static void main(String[] args) {
                    System.out.println("Hello, Java in Monaco!");
                }
            }`,
            python:`
            def main():
                print("Hello, Python in Monaco!")
            
            if __name__ == "__main__":
                main()`
          },
          testCaseHint: [
            "2 <= nums.length <= 104",
            "-109 <= nums[i] <= 109"
          ]
  },
  {
    id: 12,
    title: '整数转罗马数字',
    description: '罗马数字包含以下七种字符： I， V， X， L，C，D 和 M。给定一个整数，将其转为罗马数字。',
    difficulty: 2,
    tags: ['数学', '字符串'],
    template: {
            cpp : `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`,
          java:`
            public class Main {
                public static void main(String[] args) {
                    System.out.println("Hello, Java in Monaco!");
                }
            }`,
            python:`
            def main():
                print("Hello, Python in Monaco!")
            
            if __name__ == "__main__":
                main()`
          },
          testCaseHint: [
            "2 <= nums.length <= 104",
            "-109 <= nums[i] <= 109"
          ]
  },
  {
    id: 13,
    title: '罗马数字转整数',
    description: '罗马数字包含以下七种字符: I， V， X， L，C，D 和 M。给定一个罗马数字，将其转换成整数。',
    difficulty: 1,
    tags: ['数学', '字符串'],
    template: {
            cpp : `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`,
          java:`
            public class Main {
                public static void main(String[] args) {
                    System.out.println("Hello, Java in Monaco!");
                }
            }`,
            python:`
            def main():
                print("Hello, Python in Monaco!")
            
            if __name__ == "__main__":
                main()`
          },
          testCaseHint: [
            "2 <= nums.length <= 104",
            "-109 <= nums[i] <= 109"
          ]
  }
];

// 生成题目列表(仅基础信息)
export const generateProblemList = (email, solvedStatus, page, pageSize, sortBy = 1, difficulty = 0, searchQuery = '', count = problemData.length) => {
  
  // 获取用户已解决题目ID列表
  const userStat = userStats.find(u => u.email === email);

  // 先筛选题目
  let filteredData = [];
  if (userStat) {
    if (solvedStatus === 1) {
      filteredData = problemData.filter(data => 
        userStat.solvedProblems.includes(data.id.toString())
      );
    } else if (solvedStatus === 2) {
      filteredData = problemData.filter(data => 
        userStat.attemptingProblems.includes(data.id.toString())
      );
    }
    else {
        filteredData = problemData;
    }
    // solvedStatus为0时，保留全部题目
  }else {
        filteredData = problemData;
  }

  // 生成题目列表并应用排序
  let result = filteredData.map(data => {
    // 检查缓存
    if (problemCache.has(data.id)) {
      const cached = problemCache.get(data.id);
      const p = new problem.Problem();
      p.setId(cached.getId());
      p.setTitle(cached.getTitle());
      p.setDifficulty(cached.getDifficulty());
      p.setAcceptanceRate(cached.getAcceptanceRate());
      return p;
    }

    // 生成基础题目信息
    const p = new problem.Problem();
    p.setId(data.id);
    p.setTitle(data.title);
    p.setDifficulty(data.difficulty);
    p.setAcceptanceRate(data.acceptanceRate);
    return p;
  });
  
  // 应用排序
  switch(sortBy) {
    case 1:
      result.sort((a, b) => a.getId() - b.getId());
      break;
    case 2:
      result.sort((a, b) => a.getDifficulty() - b.getDifficulty());
      break;
    default:
      result.sort((a, b) => a.getId() - b.getId());
  }
  // 难度筛选
  let filtered = [];
  if (difficulty > 0) {
      filtered = result.filter(p => {
        const match = p.getDifficulty() === difficulty;
        return match;
      });
    }
    else {
        filtered = result;
    }
  // 分页处理
  const start = (page - 1) * pageSize
  const end = start + pageSize
  return {
    problems: filtered.slice(start, end),
    total: filtered.length
  }
}

// 生成题目详情(完整信息)
export const generateProblemDetail = (id) => {
  const data = problemData.find(p => p.id === id)
  if (!data) return null

  // // 检查缓存
  // if (problemCache.has(id)) {
  //   return problemCache.get(id)
  // }

  // 生成完整题目信息
  const detail = new problem.ProblemDetail()
  detail.setId(data.id)
  detail.setTitle(data.title)
  detail.setDescription(data.description)
  detail.setDifficulty(data.difficulty)
  detail.setTagsList(data.tags)
  if (data.template) {
    Object.entries(data.template).forEach(([lang, code]) => {
      detail.getTemplatesMap().set(lang, code);
    });
  }
  detail.setTestCaseHintList(data.testCaseHint);

  // 添加测试用例
  if (data.testCases && data.testCases.length) {
    data.testCases.forEach(testCase => {
      const tc = new problem.TestCase()
      tc.setInput(testCase.input)
      tc.setOutput(testCase.output)
      if (testCase.explanation) {
        tc.setExplanation(testCase.explanation)
      }
      detail.addTestCases(tc)
    })
  }
  // 存入缓存
  // problemCache.set(id, p)
  return detail
}

const submission = [
  {
    id: "1",
    accepted: 'accepted',
    time: '2025-01-01 12:22',
    language: 'cpp',
    time_cost: 1.1,
    memory_cost: 1.1,
    code: `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`
  },{
    id: "2",
    accepted: 'wrong_answer',
    time: '2025-01-01 12:22',
    language: 'cpp',
    time_cost: 1.1,
    memory_cost: 1.1,
    code: `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`
  },{
    id: "3",
    accepted: 'time_limit_exceeded',
    time: '2025-01-01 12:22',
    language: 'cpp',
    time_cost: 1.1,
    memory_cost: 1.1,
    code: `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`
  },{
    id: "4",
    accepted: 'memory_limit_exceeded',
    time: '2025-01-01 12:22',
    language: 'cpp',
    time_cost: 1.1,
    memory_cost: 1.1,
    code: `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`
  },{
    id: "5",
    accepted: 'runtime_error',
    time: '2025-01-01 12:22',
    language: 'cpp',
    time_cost: 1.1,
    memory_cost: 1.1,
    code: `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`
  },{
    id: "6",
    accepted: 'compile_error',
    time: '2025-01-01 12:22',
    language: 'cpp',
    time_cost: 1.1,
    memory_cost: 1.1,
    code: `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`
  },{
    id: "7",
    accepted: 'accepted',
    time: '2025-01-01 12:22',
    language: 'cpp',
    time_cost: 1.1,
    memory_cost: 1.1,
    code: `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`
  },{
    id: "8",
    accepted: 'accepted',
    time: '2025-01-01 12:22',
    language: 'cpp',
    time_cost: 1.1,
    memory_cost: 1.1,
    code: `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`
  },{
    id: "9",
    accepted: 'accepted',
    time: '2025-01-01 12:22',
    language: 'cpp',
    time_cost: 1.1,
    memory_cost: 1.1,
    code: `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`
  },{
    id: "10",
    accepted: 'accepted',
    time: '2025-01-01 12:22',
    language: 'cpp',
    time_cost: 1.1,
    memory_cost: 1.1,
    code: `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`
  },{
    id: "11",
    accepted: 'accepted',
    time: '2025-01-01 12:22',
    language: 'cpp',
    time_cost: 1.1,
    memory_cost: 1.1,
    code: `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`
  },{
    id: "12",
    accepted: 'accepted',
    time: '2025-01-01 12:22',
    language: 'cpp',
    time_cost: 1.1,
    memory_cost: 1.1,
    code: `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`
  },{
    id: "13",
    accepted: 'accepted',
    time: '2025-01-01 12:22',
    language: 'cpp',
    time_cost: 1.1,
    memory_cost: 1.1,
    code: `
            #include <iostream>
            
            int main() {
                std::cout << "Hello, C++ in Monaco!" << std::endl;
                return 0;
            }`
  }
];

export const getSubmissions = (page = 1, pagesize = 10) => {
  const start = (page - 1) * pagesize;
  const end = start + pagesize;
  const paginatedSubmissions = submission.slice(start, end);
  
  return {
    list: paginatedSubmissions.map(sub => {
      const result = new problem.SubmitResult();
      result.setId(sub.id);
      result.setAccepted(sub.accepted);
      result.setLanguage(sub.language);
      result.setTime(sub.time);
      return result;
    }),
    total: submission.length
  };
};

export const getSubmissionsDetail = (id) => {
  const detail = submission.find(it => it.id === id);
  return detail;
};
